package org.iartisan.thought.web.tag;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.iartisan.thought.web.tag.utils.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * <p>
 * tags
 *
 * @author King
 * @since 2017/12/20
 */
@Component
public class TagCodeDirective implements TemplateDirectiveModel {

    private static final String topic_end = "topic_end";

    private static final String topic_fine = "topic_fine";

    private static final String topic_top = "topic_top";

    private static final String topic_warm_channel = "topic_warm_channel";

    private static final String datetime = "datetime";

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        TemplateModel codeModel = (TemplateModel) map.get("code");
        TemplateModel valueModel = (TemplateModel) map.get("value");
        if (null != codeModel && null != valueModel) {
            String code = codeModel.toString();
            String value = valueModel.toString();
            Writer out = environment.getOut();
            if (topic_end.equals(code)) {
                TopicEndDirective.render(out, value);
            } else if (datetime.equals(code)) {
                DatetimeDirective.render(out, value);
            } else if (topic_fine.equals(code)) {
                TopicFineDirective.render(out, value);
            } else if (topic_top.equals(code)) {
                TopicTopDirective.render(out, value);
            } else if (topic_warm_channel.equals(code)) {
                TopicWarmChannelDirective.render(out, value);
            }
            templateDirectiveBody.render(out);
        }
    }
}
